package com.project.webservice.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.webservice.dto.*;
import com.project.webservice.entity.TbRfidSysConditionRidName;
import com.project.webservice.entity.TbRfidSysConditionRidSerial;
import com.project.webservice.entity.TbRfidSysConditionTidUid;
import com.project.webservice.entity.TbRfidSysConditionTidXuhao;
import com.project.webservice.mapper.RfidRunMapper;
import com.project.webservice.service.*;
import com.project.webservice.util.JSONUtils;
import com.project.webservice.util.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class RfidRunServiceImpl implements RfidRunService {
    @Resource
    private RfidRunMapper rfidRunMapper;
    @Resource
    private TbRfidSysConditionRidNameService tbRfidSysConditionRidNameService;
    @Autowired
    private TbRfidSysConditionRidSerialService tbRfidSysConditionRidSerialService;
    @Resource
    private TbTidRunDayService tbTidRunDayService;
    @Resource
    private TbRfidSysConditionTidUidService tbRfidSysConditionTidUidService;
    @Autowired
    private TbRfidSysConditionTidXuhaoService tbRfidSysConditionTidXuhaoService;

    /**
     * 基站营运质量报告(一个基站多天)GET_QUALITY_RID_DAYs
     * @param searchGetQualityRidDayDto
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getQualityRidDays(SearchGetQualityRidDayDto searchGetQualityRidDayDto){
        log.info("getQualityRidDays：{}",searchGetQualityRidDayDto);
        List<List<?>> results = rfidRunMapper.getQualityRidDays(searchGetQualityRidDayDto);
        //结果集
        List<GetQualityRidDayDto> list = (List<GetQualityRidDayDto>) results.get(0);
        //总条数
        List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
        Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
        return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");
    }

    /**
     * 基站营运质量报告(多个基站一天)GET_QUALITY_RIDs_DAY
     * @param searchGetQualityRidDayDto
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getQualityRidsDay(SearchGetQualityRidDayDto searchGetQualityRidDayDto){
        log.info("getQualityRidsDay：{}",searchGetQualityRidDayDto);
        List<List<?>> results = rfidRunMapper.getQualityRidsDay(searchGetQualityRidDayDto);
        //结果集
        List<GetQualityRidDayDto> list = (List<GetQualityRidDayDto>) results.get(0);
        //总条数
        List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
        Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
        return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");
    }


    /**
     * 基站营运质量报告(多个基站一天,按照RID_NAME查询)GET_QUALITY_RIDs_DAY_by_RID_NAME
     * @param searchGetQualityRidDayDto
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getQualityRidsDayByRidName(SearchGetQualityRidDayDto searchGetQualityRidDayDto) {
        log.info("getQualityRidsDayByRidName：{}", searchGetQualityRidDayDto);
        if (StringUtils.isBlank(searchGetQualityRidDayDto.getRID_NAME())) {
            //执行RFID_RUN.dbo.GET_QUALITY_RIDs_DAY
            return getQualityRidsDay(searchGetQualityRidDayDto);
        } else {
            //先插入GJ_BUS_CONDITION.dbo.TB_RFID_SYS_CONDITION_RID_NAME
            String[] ridNames = StringUtils.split(searchGetQualityRidDayDto.getRID_NAME(), ",");
            String conditionId = UUID.randomUUID().toString();
            List<TbRfidSysConditionRidName> tbRfidSysConditionRidNames = new ArrayList<>();
            for (String ridName : ridNames) {
                tbRfidSysConditionRidNames.add(new TbRfidSysConditionRidName(conditionId, ridName));
            }
            // 调用单独的方法保存数据到gjbuscondition数据源
            boolean isSave = saveRidNameConditions(tbRfidSysConditionRidNames);
            log.info("保存RID_NAME条件数据结果: {}, conditionId: {}", isSave, conditionId);
            //执行RFID_RUN.dbo.GET_QUALITY_RIDs_DAY_by_RID_NAME
            List<List<?>> results = rfidRunMapper.getQualityRidsDayByRidName(searchGetQualityRidDayDto);
            //结果集
            List<GetQualityRidDayDto> list = (List<GetQualityRidDayDto>) results.get(0);
            //总条数
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count, true, CollUtil.isNotEmpty(list) ? JSONUtils.writeExcludeNull(list) : null, "查询成功");

        }
    }
        /**
         * 基站营运质量报告(多个基站一天,按照RID_SERIAL查询)GET_QUALITY_RIDs_DAY_by_RID_SERIAL
         * @param searchGetQualityRidDayDto
         * @return
         */
        @DS("rfidrun")
        public WebServiceR getQualityRidsDayByRidSerial(SearchGetQualityRidDayDto searchGetQualityRidDayDto){
            log.info("getQualityRidsDayByRidSerial：{}",searchGetQualityRidDayDto);
            if(StringUtils.isBlank(searchGetQualityRidDayDto.getRID_SERIAL())){
                //执行RFID_RUN.dbo.GET_QUALITY_RIDs_DAY
                return getQualityRidsDay(searchGetQualityRidDayDto);
            }else{
                //先插入GJ_BUS_CONDITION.dbo.TB_RFID_SYS_CONDITION_RID_NAME
                String[] ridSerials = StringUtils.split(searchGetQualityRidDayDto.getRID_SERIAL(),",");
                String conditionId = UUID.randomUUID().toString();
                List<TbRfidSysConditionRidSerial> rfidSysConditionRidSerials = new ArrayList<>();
                for(String ridSerial:ridSerials){
                    rfidSysConditionRidSerials.add(new TbRfidSysConditionRidSerial(conditionId,ridSerial));
                }
                // 调用单独的方法保存数据到gjbuscondition数据源
                boolean isSave = saveRidSerialConditions(rfidSysConditionRidSerials);
                log.info("保存RID_SERIAL条件数据结果: {}, conditionId: {}", isSave, conditionId);
                //执行RFID_RUN.dbo.GET_QUALITY_RIDs_DAY_by_RID_SERIAL
                List<List<?>> results = rfidRunMapper.getQualityRidsDayByRidSerial(searchGetQualityRidDayDto);
                //结果集
                List<GetQualityRidDayDto> list = (List<GetQualityRidDayDto>) results.get(0);
                //总条数
                List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
                Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
                return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");

            }
    }

    /**
     * //电子标签营运质量报告(多张电子标签一天，按照TID_UID查询) GET_QUALITY_TIDs_DAY_by_TID_UID
     * @param searchGetQualityTidDayDto
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getQualityTidsDayByTidUid(SearchGetQualityTidDayDto searchGetQualityTidDayDto){
        log.info("getQualityTidsDayByTidUid：{}",searchGetQualityTidDayDto);
        if(StringUtils.isBlank(searchGetQualityTidDayDto.getTID_UID())){ //tid_uid为空
            Page page = new Page(StringUtils.isNotBlank(searchGetQualityTidDayDto.getPage())? Long.parseLong(searchGetQualityTidDayDto.getPage()): 1,
                    StringUtils.isNotBlank(searchGetQualityTidDayDto.getPageCount())? Long.parseLong(searchGetQualityTidDayDto.getPageCount()): 10);            //执行RFID_RUN.dbo.GET_QUALITY_TIDs_DAY
            IPage<TbTidRunDayDto> ipage = tbTidRunDayService.getQualityTidsDay(page, searchGetQualityTidDayDto);
            if(ipage != null){
                return WebServiceR.result((int)ipage.getTotal(),
                        true,CollUtil.isNotEmpty(ipage.getRecords())?
                                JSONUtils.write(page.getRecords()):null, "");

            }else{
                return  WebServiceR.result(0,
                        true,null, "");

            }
        }else{
            //先插入TB_RFID_SYS_CONDITION_TID_UID
            String[] tidUids = StringUtils.split(searchGetQualityTidDayDto.getTID_UID(),",");
            String conditionId = UUID.randomUUID().toString();
            List<TbRfidSysConditionTidUid> tbRfidSysConditionTidUids = new ArrayList<>();
            for(String tidUid:tidUids){
                tbRfidSysConditionTidUids.add(new TbRfidSysConditionTidUid(conditionId,tidUid));
            }
            // 调用单独的方法保存数据到gjbuscondition数据源
            boolean isSave = saveTidUidConditions(tbRfidSysConditionTidUids);
            log.info("保存TID_UID条件数据结果: {}, conditionId: {}", isSave, conditionId);

            //执行RFID_RUN.dbo.GET_QUALITY_TIDs_DAY_by_TID_UID
            List<List<?>> results = rfidRunMapper.getQualityTidsDayByTidUid(searchGetQualityTidDayDto);
            //结果集
            List<TbTidRunDayDto> list = (List<TbTidRunDayDto>) results.get(0);
            //总条数
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");

        }
    }

    /**
     * 电子标签营运质量报告(多张电子标签一天，按照TID_xuhao查询) GET_QUALITY_TIDs_DAY_by_TID_xuhao
     * @param searchGetQualityTidDayDto
     * @return
     */
    public WebServiceR getQualityTidsDayByTidXuhao(SearchGetQualityTidDayDto searchGetQualityTidDayDto){
        log.info("getQualityTidsDayByTidXuhao：{}",searchGetQualityTidDayDto);
        if(StringUtils.isBlank(searchGetQualityTidDayDto.getTID_xuhao())){
            Page page = new Page(StringUtils.isNotBlank(searchGetQualityTidDayDto.getPage())? Long.parseLong(searchGetQualityTidDayDto.getPage()): 1,
                    StringUtils.isNotBlank(searchGetQualityTidDayDto.getPageCount())? Long.parseLong(searchGetQualityTidDayDto.getPageCount()): 10);            //执行RFID_RUN.dbo.GET_QUALITY_TIDs_DAY
            IPage<TbTidRunDayDto> ipage = tbTidRunDayService.getQualityTidsDay(page, searchGetQualityTidDayDto);
            if(ipage != null){
                return WebServiceR.result((int)ipage.getTotal(),
                        true,CollUtil.isNotEmpty(ipage.getRecords())?
                                JSONUtils.write(page.getRecords()):null, "");

            }else{
                return  WebServiceR.result(0,
                        true,null, "");

            }
        }else{
            String[] tidxuhaos = StringUtils.split(searchGetQualityTidDayDto.getTID_xuhao(),",");
            String conditionId = UUID.randomUUID().toString();
            List<TbRfidSysConditionTidXuhao> tbRfidSysConditionTidXuhaos = new ArrayList<>();
            for(String tidxuhao:tidxuhaos){
                tbRfidSysConditionTidXuhaos.add(new TbRfidSysConditionTidXuhao(conditionId,tidxuhao));
            }
            // 调用单独的方法保存数据到gjbuscondition数据源
            boolean isSave = saveTidXuhaoConditions(tbRfidSysConditionTidXuhaos);
            log.info("保存TID_xuhao条件数据结果: {}, conditionId: {}", isSave, conditionId);

            //执行RFID_RUN.dbo.GET_QUALITY_TIDs_DAY_by_TID_xuhao
            List<List<?>> results = rfidRunMapper.getQualityTidsDayByTidXuhao(searchGetQualityTidDayDto);
            //结果集
            List<TbTidRunDayDto> list = (List<TbTidRunDayDto>) results.get(0);
            //总条数
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");

        }
    }





    /**
     * 基站运转情况  getRIDLiv
     * @param username
     * @param ridStatusId
     * @param ridVenderRegnum
     * @param pageNo
     * @param pageLines
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getRidLiv(String username, int ridStatusId,String ridVenderRegnum,int pageNo,int pageLines){
        log.info("getRidLiv username:{},ridStatusId:{},ridVenderRegnum:{},pageno:{},pageno,pageLines:{}",username,ridStatusId,ridVenderRegnum,pageNo,pageLines);
        //执行RFID_RUN.GET_RID_LIV
        List<List<?>> results = rfidRunMapper.getRidLiv(username,ridStatusId,ridVenderRegnum,pageNo,pageLines);
        if(CollUtil.isNotEmpty(results)) {
            //结果集
            List<GetRidLivDto> list = (List<GetRidLivDto>) results.get(0);
            //总条数
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count, true, CollUtil.isNotEmpty(list) ? JSONUtils.writeExcludeNull(list) : null, "查询成功");
        }else{
            return WebServiceR.result(0, true, null, "");
        }
    }


    /**
     * 基站运转情况(加入查询关键字:RID_NAME) getRidLivByRidName
     * @param uid
     * @param key
     * @param ridStatusId
     * @param ridVendorId
     * @param page
     * @param pageCount
     * @param ridName
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getRidLivByRidName(String uid, String key, String ridStatusId, String ridVendorId, String page, String pageCount, String ridName){
        log.info("getRidLivByRidName uid:{},key:{},ridStatusId:{},ridVendorId:{},page:{},pageCount:{},ridName:{}",uid,key,ridStatusId,ridVendorId,page,pageCount,ridName);
        if(StringUtils.isBlank(ridName)){
            return getRidLiv(uid, Integer.parseInt(ridStatusId), ridVendorId, Integer.parseInt(page), Integer.parseInt(pageCount));
        }else{
            String[] ridNames = StringUtils.split(ridName,",");
            String conditionId = UUID.randomUUID().toString();
            List<TbRfidSysConditionRidName> tbRfidSysConditionRidNames = new ArrayList<>();
            for (String name : ridNames) {
                tbRfidSysConditionRidNames.add(new TbRfidSysConditionRidName(conditionId, name));
            }
            
            // 调用单独的方法保存数据到gjbuscondition数据源
            boolean isSave = tbRfidSysConditionRidNameService.saveBatch(tbRfidSysConditionRidNames); //saveRidNameConditions(tbRfidSysConditionRidNames);
            log.info("保存RID_NAME条件数据结果: {}, conditionId: {}", isSave, conditionId);
            
            //执行RFID_RUN.dbo.GET_RID_LIVE_BY_RID_NAME
            List<List<?>> results = rfidRunMapper.getRidLivByRidName(uid, conditionId, Integer.parseInt(ridStatusId), ridVendorId, Integer.parseInt(page), Integer.parseInt(pageCount));
            List<GetRidLivDto> list = (List<GetRidLivDto>) results.get(0);
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");
        }
    }


    /**
     * 基站运转情况(加入查询关键字:RID_SERIAL)
     * @param uid
     * @param key
     * @param ridStatusId
     * @param ridVendorId
     * @param page
     * @param pageCount
     * @param ridSerial
     * @return
     */
    @DS("rfidrun")
    public WebServiceR getRidLivByRidSerial(String uid, String key, String ridStatusId, String ridVendorId, String page, String pageCount, String ridSerial){
        log.info("getRidLivByRidSerial uid:{},key:{},ridStatusId:{},ridVendorId:{},page:{},pageCount:{},ridSerial:{}",uid,key,ridStatusId,ridVendorId,page,pageCount,ridSerial);
        if(StringUtils.isBlank(ridSerial)){
            return getRidLiv(uid, Integer.parseInt(ridStatusId), ridVendorId, Integer.parseInt(page), Integer.parseInt(pageCount));
        }else{
            String[] ridSerials = StringUtils.split(ridSerial,",");
            String conditionId = UUID.randomUUID().toString();
            List<TbRfidSysConditionRidSerial> tbRfidSysConditionRidSerials = new ArrayList<>();
            for (String r : ridSerials) {
                tbRfidSysConditionRidSerials.add(new TbRfidSysConditionRidSerial(conditionId, r));
            }

            // 调用单独的方法保存数据到gjbuscondition数据源
            boolean isSave = tbRfidSysConditionRidSerialService.saveBatch(tbRfidSysConditionRidSerials); //saveRidNameConditions(tbRfidSysConditionRidNames);


            //执行RFID_RUN.dbo.Get_RID_LIV_by_RID_SERIAL
            List<List<?>> results = rfidRunMapper.getRidLivByRidSerial(uid, conditionId, Integer.parseInt(ridStatusId), ridVendorId, Integer.parseInt(page), Integer.parseInt(pageCount));
            List<GetRidLivDto> list = (List<GetRidLivDto>) results.get(0);
            List<Map<String, Object>> linesList = (List<Map<String, Object>>) results.get(1);
            Integer count = Integer.valueOf(linesList.get(0).get("lines").toString());
            return WebServiceR.result(count,true, CollUtil.isNotEmpty(list)? JSONUtils.writeExcludeNull(list):null,"查询成功");
        }
    }


    /**
     * get_Center_link
     * @return
     */
    @DS("rfidrun")
    public List<GetCenterLinkDto> getCenterLink(){
        return rfidRunMapper.getCenterLink();
    }
    /**
     * get_Center_link_detail
     * @return
     */
    @DS("rfidrun")
    public List<GetCenterLinkDetailDto> getCenterLinkDetail(){
        return rfidRunMapper.getCenterLinkDetail();
    }

    /**
     * 企业线路监测质量汇总报告
     * @param date
     * @return
     */
   @DS("gjbusresult")
       public List<ProGetTbCzxlRfidDayDto> proGetTbCzxlRfidDay(String date){
        return rfidRunMapper.proGetTbCzxlRfidDay(date);
    }

    /**
     * 电子标签进出站数据跟踪get_TID_IN_OUT_DAY
     * @param date
     * @param icon
     * @return
     */
    @DS("rfidrun")
    public List<ProGetTidInOutDayDto> proGetTidInOutDay(String date,String icon){
       log.info("proGetTidInOutDay date:{},icon:{}",date,icon);
       return rfidRunMapper.proGetTidInOutDay(date,icon);
    }
    @DS("gjbuscondition")
    @Transactional
    public boolean saveRidNameConditions(List<TbRfidSysConditionRidName> conditions) {
        try {
            log.info("开始保存RID_NAME条件数据，数量: {}", conditions.size());
            log.info("当前数据源: gjbuscondition");
            log.info("条件数据详情: {}", conditions);
            boolean result = tbRfidSysConditionRidNameService.saveBatch(conditions);
            log.info("保存RID_NAME条件数据完成，结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("保存RID_NAME条件数据失败", e);
            throw e;
        }
    }

    @DS("gjbuscondition")
    @Transactional
    public boolean saveRidSerialConditions(List<TbRfidSysConditionRidSerial> conditions) {
        try {
            log.info("开始保存RID_SERIAL条件数据，数量: {}", conditions.size());
            boolean result = tbRfidSysConditionRidSerialService.saveBatch(conditions);
            log.info("保存RID_SERIAL条件数据完成，结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("保存RID_SERIAL条件数据失败", e);
            throw e;
        }
    }

    @DS("gjbuscondition")
    @Transactional
    public boolean saveTidUidConditions(List<TbRfidSysConditionTidUid> conditions) {
        try {
            log.info("开始保存TID_UID条件数据，数量: {}", conditions.size());
            boolean result = tbRfidSysConditionTidUidService.saveBatch(conditions);
            log.info("保存TID_UID条件数据完成，结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("保存TID_UID条件数据失败", e);
            throw e;
        }
    }

    @DS("gjbuscondition")
    @Transactional
    public boolean saveTidXuhaoConditions(List<TbRfidSysConditionTidXuhao> conditions) {
        try {
            log.info("开始保存TID_xuhao条件数据，数量: {}", conditions.size());
            boolean result = tbRfidSysConditionTidXuhaoService.saveBatch(conditions);
            log.info("保存TID_xuhao条件数据完成，结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("保存TID_xuhao条件数据失败", e);
            throw e;
        }
    }
}
